﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGinnBPM.Services;
using System.Data;
using System.Data.SqlClient;

namespace NGinnBPM.Dao
{
    public class SqlTaskDbSessionFactory : ITaskDatabaseSessionFactory
    {
        public string ConnectionString { get; set; }
        public bool UseMessageBusConnection { get; set; }

        private SqlConnection OpenConnection()
        {
            var c = new SqlConnection(ConnectionString);
            c.Open();
            return c;

        }
        
        public ITaskDatabaseSession OpenSession()
        {
            if (UseMessageBusConnection)
            {
                var con = NGinnBPM.MessageBus.MessageBusContext.ReceivingConnection as IDbConnection;
                if (con != null && con.State == ConnectionState.Open && NGinnBPM.MessageBus.Impl.SqlUtil.IsSameDatabaseConnection(con.ConnectionString, ConnectionString))
                {
                    return new SqlTaskDbSession(con, null);
                }
            }
            var con1 = OpenConnection();
            var b = NGinnBPM.MessageBus.MessageBusContext.ReceivingConnection == null;
            if (b) NGinnBPM.MessageBus.MessageBusContext.AppManagedConnection = con1;
            return new SqlTaskDbSession(con1, delegate()
            {
                if (b) NGinnBPM.MessageBus.MessageBusContext.AppManagedConnection = null;
                con1.Close();
            });
        }

       

    }

    internal class SqlTaskDbSession : ITaskDatabaseSession
    {
        private IDbConnection _c;
        private Action _close;

        public SqlTaskDbSession(IDbConnection c, Action onClose)
        {
            _c = c;
            _close = onClose;
        }

        public object Connection
        {
            get { return _c; }
        }

        public void Dispose()
        {
            if (_close != null)
            {
                _close();
                _close = null;
                _c = null;
            }
        }
    }
}
